package com.cyk.service.impl;

import com.cyk.entity.Blog;
import com.cyk.entity.User;
import com.cyk.entity.vo.BlogVO;
import com.cyk.feign.UserClient;
import com.cyk.mapper.BlogMapper;
import com.cyk.service.BlogService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * (Blog)表服务实现类
 *
 * @author makejava
 * @since 2024-01-06 23:19:03
 */
@Service("blogService")
public class BlogServiceImpl implements BlogService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private ObjectMapper objectMapper;

    @Resource
    private BlogMapper blogMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Blog queryById(Long id) {
        return this.blogMapper.queryById(id);
    }

    /**
     * 新增数据
     *
     * @param blog 实例对象
     * @return 实例对象
     */
    @Override
    public Blog insert(Blog blog) {
        this.blogMapper.insert(blog);
        return blog;
    }

    /**
     * 修改数据
     *
     * @param blog 实例对象
     * @return 实例对象
     */
    @Override
    public Blog update(Blog blog) {
        this.blogMapper.update(blog);
        return this.queryById(blog.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.blogMapper.deleteById(id) > 0;
    }

    @SneakyThrows
    @Override
    public BlogVO getBlogAndUser(Long blogId, Long userId) {
        //1.获取博客信息
        Blog blog = blogMapper.queryById(blogId);
        BlogVO blogVO = new BlogVO();
        BeanUtils.copyProperties(blog, blogVO);
        //2.获取用户信息
        String userJson = userClient.user(userId);
        User user = objectMapper.readValue(userJson, User.class);
        blogVO.setUsername(user.getUsername());
        return blogVO;
    }
}
